package demo;

/**
 * 三个线程循环打印abcabcabc
 */
public class CirculPrint {

    public static void main(String[] args) throws InterruptedException {
        MyTask task1 = new MyTask('A');
        MyTask task2 = new MyTask('B');
        MyTask task3 = new MyTask('C', task1);
        task1.setNext(task2);
        task2.setNext(task3);

        new Thread(task1, "线程1").start();
        Thread.sleep(0);
        new Thread(task2, "线程2").start();
        Thread.sleep(0);
        new Thread(task3, "线程3").start();
    }

    public static class MyTask implements Runnable {
        private char printChar;
        private MyTask next;

        public MyTask(char printChar) {
            this.printChar = printChar;
        }

        public MyTask(char printChar, MyTask next) {
            this.printChar = printChar;
            this.next = next;
        }

        public void setNext(MyTask next) {
            this.next = next;
        }

        @Override
        public void run() {
            for(int i = 0; i < 5; i++){
                System.out.println(printChar);
                synchronized (next) {
                    next.notify();
                }
                if (i != 4) {
                    synchronized (this) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
